<script setup lang="ts">
import { BaseModelTreeType } from '@renderer/types'

const {
  filterPlaceholder = '',
  data = [],
  expandOnClickNode = true,
  click = () => {}
} = defineProps<{
  filterPlaceholder?: string
  data?: BaseModelTreeType
  expandOnClickNode?: boolean
  click?: (id: string) => void
}>()

const current = defineModel<string>('current')

const filterText = ref('')
const handleFilter = (value: string, data: Record<string, any>) => {
  if (!value) return true
  return data.label.toLowerCase().includes(value.toLowerCase())
}
const treeRef = ref()
watch(
  () => filterText.value,
  (val) => treeRef.value?.filter(val)
)

const isDirNode = (nodeData) => isDirConf(nodeData)

const handleNodeClick = (nodeData) => {
  current.value = nodeData?.value
  click(nodeData?.value)
}
</script>

<template>
  <div class="w-full h-full flex flex-col items-stretch">
    <div class="p-2">
      <el-input v-model="filterText" :placeholder="filterPlaceholder" clearable />
    </div>
    <el-scrollbar class="flex-1">
      <el-tree
        ref="treeRef"
        class="tree"
        :props="{ class: () => 'tree-node' }"
        :expand-on-click-node="expandOnClickNode"
        check-on-click-node
        highlight-current
        node-key="value"
        :data="data"
        :filter-node-method="handleFilter"
        :current-node-key="current"
        @node-click="handleNodeClick"
      >
        <template #default="{ data: nodeData }">
          <div :class="['pos-relative', 'w-full']">
            <div :class="['w-full', 'flex items-center gap-2', 'select-none']">
              <s-icon
                :icon-type="nodeData?.icon?.iconType"
                :icon-props="{ ...nodeData?.icon?.iconProps, color: nodeData?.color }"
              />
              <span v-if="isDirNode(nodeData)">{{ nodeData?.count }}</span>
              <s-text-ellipsis class="flex-1">{{ nodeData?.label }}</s-text-ellipsis>
            </div>
            <slot name="node-suf" :nodeData="nodeData" />
            <div
              :class="[
                'pos-absolute top-[50%] right-0 translate-y-[-50%]',
                'pr-2',
                'flex items-center',
                'backdrop-blur-sm'
              ]"
            >
              <slot name="node-float-right" :nodeData="nodeData" />
            </div>
          </div>
        </template>
      </el-tree>
    </el-scrollbar>
  </div>
</template>

<style lang="scss">
.tree {
  .tree-node {
    .el-tree-node__content {
      --el-tree-node-content-height: 3rem;
    }
  }

  .el-button {
    padding: 0.35rem;
  }
}
</style>
